/////////////////////////////////////////////
/// Implementation of the simple template "Tell me * of *"
/////////////////////////////////////////////

// fetching the log
log = context.getLog()

context.startComposing()
wildcard1 = context.getMatch(1);
wildcard2 = context.getMatch(2);

//sparqlqury
documentQuery = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> "+
"SELECT DISTINCT  ?subject ?concept "+
"WHERE { "+
"?subject a ?tmpcon . "+
"?subject rdfs:label ?tmpsub. "+
"FILTER bif:contains(?tmpsub,\""+wildcard1+"\"@en ). "+
"?tmpcon rdfs:label ?concept. }"+
"Limit 50"

context.sendMessageToUser("asking DBpedia...");

toUser = ""
errors = ""
urlglobal = "http://dbpedia.openlinksw.com:8890/sparql?default-graph-uri=http://dbpedia.org"
//urllocal = "http://139.18.2.37:8890/sparql?default-graph-uri=http://dbpedia.org"
url = urlglobal

java.util.TreeSet good = new java.util.TreeSet();
context.queryRemote(documentQuery,url).each{table ->
	if(table.errors!=null){
		errors += table.errors + " by " + table.storeName
	}else{
		table.resultRows.each{row ->

			c = row["concept"]
			//context.sendMessageToUser(c);
			if( c.toUpperCase().contains(wildcard2.toUpperCase()) ){

				sub = row["subject"];
				good.add(sub);

			}
		}
	}
}

toUser = "";
errors = "";
good.each() { instance->

	newDetailQuery =  "PREFIX foaf: <http://xmlns.com/foaf/0.1/> "+
					  "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> "+
					  "SELECT ?sublabel ?comment ?page "+
					  "WHERE {"+
					  "<"+instance+"> rdfs:label ?sublabel. FILTER (lang(?sublabel)= \"en\") . "+
					  "OPTIONAL {<"+instance+"> rdfs:comment ?comment. FILTER (lang(?comment)= \"en\") }. "+
					  "OPTIONAL {<"+instance+"> foaf:page ?page. }. "+
				 	 "}";


	context.queryRemote(newDetailQuery,url).each{table2 ->
		if(table2.errors!=null){
			errors += table.errors + " by " + table2.storeName
		}else{
			table2.resultRows.each{row2 ->


				toUser = toUser + row2["sublabel"] + ":  " +  row2["comment"]  +" Get more info: " + row2["page"] + "\n"


			}
		}
	}
}





context.stopComposing()
context.sendMessageToUser(toUser)
if(errors.length()>0){
	context.sendMessageToUser("Unfortunately some errors occured : " + errors)
}


